#include <sys/types.h>  
#include <sys/socket.h>  
#include <netinet/in.h>  
#include <arpa/inet.h>  
#include <time.h>  
#include <string.h>  
#include <stdio.h>  
#include <unistd.h>  
#include <stdlib.h>  
#include <netinet/tcp.h> 
#include <fcntl.h>
#include <errno.h>

#define FLASH_DEBUG	printf
/*
mtd0: 00020000 00010000 "BOOT"
mtd1: 00040000 00010000 "TABLE"
mtd2: 00010000 00010000 "SERIAL"
mtd3: 00010000 00010000 "V_OEM"
mtd4: 00040000 00010000 "OTA"
mtd5: 00230000 00010000 "KERNEL"
mtd6: 001b0000 00010000 "ROOTFS"
mtd7: 002b0000 00010000 "USER"
mtd8: 00010000 00010000 "BC"
mtd9: 00010000 00010000 "BD"
mtd10: 00050000 00010000 "DATA"
mtd11: 00040000 00010000 "SYSLOG"
*/


#define USER_SECTION_LEN 0x002b0000
#define UPDATE_FILE_NAME "/tmp/webupdate.bin"
#define CMD_FLASH_ERASE  "flash_eraseall /dev/mtd7"
#define CMD_FLASH_CP "flashcp "UPDATE_FILE_NAME" /dev/mtd7"	

static unsigned char ota_appfile_flag=0;
static unsigned char ota_appfile_wirte_rate=0;


unsigned char ota_appfile_flag_get(void)
{
	return ota_appfile_flag;
}

void ota_appfile_flag_set(void)
{
	ota_appfile_flag= 1;
}

void ota_appfile_flag_clear(void)
{
	ota_appfile_flag= 0;
}

unsigned char ota_appfile_write_rate(void)
{
	return ota_appfile_wirte_rate;
}

static int plat_flash_wirte(void)
{
	int ret=0;
	char *arg;
	arg= CMD_FLASH_ERASE;
	printf("flash start erase\n");
	ota_appfile_wirte_rate=10;
	ret= system(arg);	
	if(ret != 0 ){
		printf("flash erase faild\n");
		return 0;
	}
	ota_appfile_wirte_rate=40;
	arg= CMD_FLASH_CP;
	printf("flash start write\n");
	ret= system(arg);		
	if(ret != 0 ){
		ota_appfile_wirte_rate=0;
		printf("flash write err\n");
	}
	printf("flash write ok\n");
	ota_appfile_wirte_rate=100;
	return 0;
}



unsigned char wirte_userbin_file(unsigned char *p_dta,unsigned int len)
{
	FILE * fp;
	unsigned char ret=0;
	if(0 != ota_appfile_flag_get()){
		printf("file exits\n");
		return 0;
	}
	if(len > 0 && len < USER_SECTION_LEN){
		fp = fopen(UPDATE_FILE_NAME,"w");
		if(fp != NULL ){
			int wlen = fwrite(p_dta, 1, len, fp);
			fclose(fp);
			if(wlen == len){
				ret=1;
				ota_appfile_flag_set();
			}
		}	
	}
	return ret;
}



void fw_update_start(unsigned char *p_dta,unsigned int len)
{
	wirte_userbin_file(p_dta, len);
}

void fw_update_loop(void)
{
	if(ota_appfile_flag_get()  ==  1){
		if (0 == plat_flash_wirte()){
			user_reboot(5);
		}
		ota_appfile_flag_clear();
	}
}





